import React, {
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
} from 'react';
import { PlayCircleOutlined } from '@ant-design/icons';
import setting from './setting';
import styles from './index.less';

const Demo = forwardRef(({ width, height, config = {}, data }, ref) => {
  const [msg, setMsg] = useState('hello');
  const {
    theme,
    rectAngle = 30,
    angle = 45,
    backgroundColor = '#2949B1',
  } = config;

  let background = '';
  if (backgroundColor.indexOf('-') > 0) {
    background = `linear-gradient(${angle}deg, ${backgroundColor.replace(
      '-',
      ','
    )})`;
  } else {
    background = backgroundColor;
  }

  const style = {
    width,
    height,
    background,
    fontSize: 32,
  };

  if (theme === 'circle') {
    style.borderRadius = '50%';
  }
  if (theme === 'rect') {
    const rectLength = width - Math.floor(height * 0.578);
    style.transform = `skew(-${rectAngle}deg)`;
    style.marginLeft = Math.floor((height * 0.578) / 2);
    style.width = rectLength > 0 ? rectLength : 0;
  }

  useEffect(() => {
    setTimeout(() => {
      setMsg('hello world');
    }, 3000);
  }, []);

  useImperativeHandle(ref, () => ({
    useWatchDataPool: (key, datapool) => {
      // eslint-disable-next-line no-console
      console.log('监听变量变化', key, datapool);
    },
    useWatchDataLoadStatus: (status) => {
      /**
       * API、数据库数据请求状态
       * pending: 请求已发起，等待返回
       * fulfilled: 请求返回成功
       * rejected: 请求返回失败
       */
      // eslint-disable-next-line no-console
      console.log(status);
    },
  }));

  return (
    <div className={styles.box}>
      <div style={style}>
        {msg}
        {data &&
          data.map((i) => (
            <p key={`${i.name}-${i.value}`}>
              <PlayCircleOutlined />
              {`${i.name}-${i.value}`}
            </p>
          ))}
        {config.isProd ? 'production' : 'test'}
      </div>
    </div>
  );
});

Demo.setting = setting;

/**
 * 自定义配置
 *  1. 对于只有当前组件才使用的样式配置，可以集成自定义配置组件
 *  2. 自定义配置组件 props 参数必须实现：  value, onChange
 *
 */
Demo.styleConfig = {
  EnvSwitch: ({ value, onChange }) => (
    <div
      onClick={() => {
        onChange(!value);
      }}
    >
      {value ? 'production' : 'test'}
    </div>
  ),
};
export default Demo;
